package rsa;

import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;

public class RsaMain {

    public static void main(String[] args) {
        try {
            String text = "上山打老虎";
            boolean usePKCS8 = true; // usePKCS8=true表示是否成PKCS8格式的公私秘钥,否则乘车PKCS1格式的公私秘钥
            String filePath = RsaUtil.class.getClassLoader().getResource("").getPath();
            System.out.printf("文件路径：%s\n", filePath);// 存放pem,crt,pfx等文件的目录
            byte[] publicKey, privateKey;// 公钥和私钥

            // 生成公私钥
            Object[] rsaKey = RsaUtil.generateRsaKey(usePKCS8); // usePKCS8=true表示是否成PKCS8格式的公私秘钥,否则乘车PKCS1格式的公私秘钥
            publicKey = (byte[]) rsaKey[0];
            privateKey = (byte[]) rsaKey[1];
            // 从Pem文件读取公私钥，filePath是文件目录
            // publicKey = RsaUtil.readFromPem(filePath + "rsa.pub");
            // privateKey = RsaUtil.readFromPem(filePath + "rsa.pem");
            // 从pfx文件读取公私钥，filePath是文件目录
            // Object[] rsaKey = RsaUtil.readFromPfx(filePath + "demo.pfx",
            // "123456");
            // publicKey = (byte[]) rsaKey[0];
            // privateKey = (byte[]) rsaKey[1];
            // 从crt文件读取公钥（crt文件中不包含私钥），filePath是文件目录
            // publicKey = RsaUtil.readPublicKeyFromCrt(filePath + "demo.crt");
            // privateKey = RsaUtil.readFromPem(filePath + "demo.key");

            // 保存到pem文件，filePath是保存目录
            RsaUtil.writeToPem(publicKey, false, filePath + "rsa.pub");
            RsaUtil.writeToPem(privateKey, true, filePath + "rsa.pem");

            // Pkcs8格式公钥转换为Pkcs1格式公钥
            publicKey = RsaUtil.pkcs8ToPkcs1(false, publicKey);
            // Pkcs8格式私钥转换为Pkcs1格式私钥
            privateKey = RsaUtil.pkcs8ToPkcs1(true, privateKey);
            // Pkcs1格式公钥转换为Pkcs8格式公钥
            publicKey = RsaUtil.pkcs1ToPkcs8(false, publicKey);
            // Pkcs1格式私钥转换为Pkcs8格式私钥
            privateKey = RsaUtil.pkcs1ToPkcs8(true, privateKey);

            RSAPublicKey rsaPublicKey = RsaUtil.generatePublicKey(usePKCS8, publicKey);
            RSAPrivateKey rsaPrivateKey = RsaUtil.generatePrivateKey(usePKCS8, privateKey);

            String encryptText = RsaUtil.rsaEncrypt(text, rsaPublicKey);
            System.out.printf("【%s】经过【RSA】加密后：%s\n", text, encryptText);

            String decryptText = RsaUtil.rsaDecrypt(encryptText, rsaPrivateKey);
            System.out.printf("【%s】经过【RSA】解密后：%s\n", encryptText, decryptText);

            String signature = RsaUtil.sign(text, rsaPrivateKey, "MD5");
            System.out.printf("【%s】经过【RSA】签名后：%s\n", text, signature);

            boolean result = RsaUtil.verify(text, rsaPublicKey, signature, "MD5");
            System.out.printf("【%s】的签名【%s】经过【RSA】验证后结果是：" + result, text, signature);

        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}
